package com.itqian.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itqian.common.exception.EorderException;
import com.itqian.common.exception.ResponseEnum;
import com.itqian.common.utils.JWTUtils;
import com.itqian.common.utils.ResultVOUtil;
import com.itqian.system.entity.Constants;
import com.itqian.system.entity.User;
import com.itqian.system.form.AddUserForm;
import com.itqian.system.form.UserRegisterForm;
import com.itqian.system.mapper.UserMapper;
import com.itqian.system.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itqian.system.vo.AdminUserVO;
import com.itqian.system.vo.UserVO;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyun.tea.*;
import com.aliyun.dysmsapi20170525.*;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.*;
import com.aliyun.teaopenapi.models.*;
import org.springframework.util.DigestUtils;

import java.util.*;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author shishuqian
 * @since 2022-03-21
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    /**
     *
     * @author shishuqian
     * @desc 随机生成6位数字验证码
     */
    public static String randomCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }

    @Override
    public String sendSms(String phone,String akId,String akSecret) throws Exception{
        //生成6位数字验证码
        String code = randomCode();


        com.aliyun.dysmsapi20170525.Client client = createClient(akId, akSecret);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName("阿里云短信测试")
                .setTemplateCode("SMS_154950909")
                //手机号
                .setPhoneNumbers(phone)
                //模板里的code参数
                .setTemplateParam("{\"code\":" + code + "}");
        // 复制代码运行请自行打印 API 的返回值
        SendSmsResponse response = client.sendSms(sendSmsRequest);
        SendSmsResponseBody body = response.getBody();
        //返回信息中的  code="OK"  代表发送成功，其它为失败
        if (!body.getCode().equals("OK")){
            throw new EorderException(ResponseEnum.SMS_SEND_FAIL.getMsg());
        }

        return code;
    }

    @Override
    public User getByPhone(String phone) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",phone);
        return userMapper.selectOne(wrapper);
    }

    @Override
    public Integer addUser(AddUserForm form) {

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",form.getUsername());
        User one = userMapper.selectOne(wrapper);
        //此用户名如果已被注册
        if (one != null){
            throw new EorderException(ResponseEnum.USER_REGISTERED.getMsg());
        }
        //生成8位随机字符，用做md5盐
        String salt = RandomStringUtils.random(8,true,true);
        //对密码进行md5加盐加密
        String md5 = DigestUtils.md5DigestAsHex((salt + form.getPassword()).getBytes());
        User user = new User();
        user.setUsername(form.getUsername())
                .setPassword(md5)
                .setNickname(form.getNickname())
                .setSalt(salt);
        if (form.getRole().equals(Constants.SELLER)){
            user.setRole("user_seller");
        }else if (form.getRole().equals(Constants.RUNNER)){
            user.setRole("user_runner");
        }else {
            user.setRole("user");
        }

        int insert = userMapper.insert(user);
        //返回新增数据的主键id(mp已经封装好了方法)
        return user.getUserId();
    }

    @Override
    public Map<String, Object> userList(Integer page,Integer size) {
        Page<User> userPage = new Page<>(page, size);
        Page<User> selectPage = userMapper.selectPage(userPage, null);

        List<AdminUserVO> list = new ArrayList<>();

        for (User record : selectPage.getRecords()) {
            AdminUserVO vo = new AdminUserVO();
            BeanUtils.copyProperties(record,vo);
            list.add(vo);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("content",list);
        map.put("size",selectPage.getSize());
        map.put("total",selectPage.getTotal());

        return map;
    }


    @Override
    public boolean editRole(Integer userId, Set<String> roles) {
        String join = StringUtils.join(roles.toArray(), "_");
        User user = userMapper.selectById(userId);
        //修改用户权限，保存
        user.setRole(join);
        int i = userMapper.updateById(user);
        return i==1;
    }

}
